const express = require("express")
const router = express.Router()
const jwt = require("jsonwebtoken")

// 连接数据库
const mongoose = require("mongoose")

const url = "mongodb://127.0.0.1:27017/shopApp"
mongoose.connect(url).then(() => {
    console.log("链接成功数据库")
})
const User = mongoose.model("user")

// 登录接口
router.post("/login", async (req, res, next) => {
    // token登录
    let token = req.header("Authorization")
    // if (token) {
    //     console.log("token", req.header("Authorization"))
    //     token = req.header("Authorization").split(" ")[1]
    //     jwt.verify(token, "mark hello haha", (err, data) => {
    //         if (err) {
    //             console.log("err", err)
    //             res.status(401).json({ msg: err.message })
    //         } else {
    //             console.log("data", data)
    //             res.status(200).json({
    //                 msg: "登陆成功"
    //             })
    //         }
    //     })
    // } else {
    // 用户名登录
    let { password, username } = req.body
    console.log('1111aa', req.body)
    if (password && username) {

        const [findOne] = await User.find(
            { password, username },
            { _id: 1, username: 1, password: 1, }
        )
        console.log(findOne, 'findOne')
        if (findOne) {
            res.status(200).json({
                msg: "登录成功",
                code: 200,
                token: "Bearer " +
                    jwt.sign(
                        {
                            id: findOne._id.toString(),
                            password: findOne.password,
                            username: findOne.username
                        }, "mark hello haha", {
                        expiresIn: "30d"
                    }
                    )
            })
        } else {
            res.status(200).json({ msg: "用户名或者密码错误" })
        }

    } else {
        res.status(200).json({ msg: "参数错误" })
    }

    // }
})


module.exports = router